package com.opennetexam.manager.utils;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.reader.UnicodeReader;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 奶茶
 * Created on 2017/11/15.
 */
public class FileUtil {

    private static final Logger logger = Logger.getLogger(FileUtil.class);

    /**
     * Gets file content.
     *
     * @param url the url
     * @return the file content
     */
    public static String getFileContent(String url) {
        File file = new File(url);
        StringBuilder sb = new StringBuilder();
        try (InputStream in = new FileInputStream(file);BufferedReader reader = new BufferedReader( new UnicodeReader(in));){
            //new UnicodeReader(in) 除去BOM头信息
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                sb.append(tempString);
            }
        } catch (IOException e) {
            logger.error("IOException",e);
        }
        return sb.toString();
    }

    public static String readFileContent(String url){
        File file = new File(url);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try (FileInputStream in = new FileInputStream(file)){
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException",e);
        } catch (IOException e) {
            logger.error("IOException",e);
        }
        return new String(filecontent);
    }

    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static Boolean deleteFile(String sPath) {
        Boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 删除目录（文件夹）以及目录下的文件
     * @param   sPath 被删除目录的文件路径
     * @return  目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith("/")) {
            sPath = sPath + "/";
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        Boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {break;}
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {break;}
            }
        }
        if (!flag) {return false;}
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 上传并解压考试计划包
     * @param file
     * @return 解压缩后的文件夹层级数组
     */
    public static Map<String,Object> uploadFile(File file){
        //上传文件
        String path = ExamSitePath.rootPath;
        String filename = file.getName();
        Map<String,Object> fileMap = new HashMap<>();
        String savePath = path + "/" + filename;
        String filePath = "";
        try {
            //BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(savePath)));
            //stream.write(bytes);
            //stream.close();

            //解压文件到指定目录 解压密码从压缩文件注释中获取
            filePath = path + "/examFile";
            fileMap = ZipUtils.unzip(savePath, filePath, "");

        } catch (Exception e) {
            logger.info("UploadFileException",e);
        }finally {
            deleteFile(savePath);
            deleteDirectory(filePath);
        }

        //压缩包路径
        fileMap.put("zipPackagePath",savePath);
        //解压后存放的路径
        fileMap.put("examPlanFolder",filePath);

        return fileMap;
    }

    /**
     * 判断文件是否存在
     * @param filePath
     * @return
     */
    public static Boolean isFileExsit(String filePath){
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * 判断该路径下的文件夹是否存在  不存在就创建
     * @param filePath
     */
    public static void createDirectory(String filePath){
        Boolean fileExsit = isFileExsit(filePath);
        if(!fileExsit){
            new File(filePath).mkdirs();
        }
    }

    /**
     * 复制图片到一个新文件夹下
     * @param filePath
     * @param imgUrl
     */
    public static void copyImage(String basePath,String imagePath,String filePath,String imgUrl){
        //判断一个图片文件夹是否存在
        File file = new File(basePath + imagePath +imgUrl.split("/")[0]);
        //文件源地址
        String newUrl = basePath + imagePath + imgUrl;
        if(!file.exists()){
            file.mkdirs();
            copyFile(filePath,newUrl);
        }else{
            copyFile(filePath,newUrl);
        }
    }

    /**
     * 向指定路径下写照片
     * @param photoFilePath 写入照片全路径 ../../xxx.jpg
     * @param photoByte 照片文件的base64字节码
     */
    public static void writePhoto(String photoFilePath,String photoByte){
        //判断该照片的父文件夹是否存在 不存在创建
        File photoFile = new File(photoFilePath);
        File parentFile = photoFile.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        //如果存在照片 不处理,不存在就创建 并写入
        if(!photoFile.exists()){
            try ( FileOutputStream outputStream = new FileOutputStream(photoFile);){
                photoFile.createNewFile();
                //写入
                BASE64Decoder base64Decoder = new BASE64Decoder();
                outputStream.write(base64Decoder.decodeBuffer(photoByte));
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将文件输入流转换为base64字符串
     * @param fileInputStream
     * @return
     */
    public static String streamToBase64String(BufferedInputStream fileInputStream) throws IOException {
        byte[] buffer = new byte[1024];
        fileInputStream.read(buffer);
        fileInputStream.close();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String encode = base64Encoder.encode(buffer);
        logger.info("学生照片转码后"+encode);
        return encode;
    }

    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        BufferedInputStream inStream = null;
        BufferedOutputStream fs = null;
        try {
            int byteread = 0;
            File oldfile = new File(oldPath);
            //文件存在时
            if (oldfile.exists()) {
                //读入原文件
                inStream = new BufferedInputStream(new FileInputStream(oldPath));
                fs = new BufferedOutputStream(new FileOutputStream(newPath));
                byte[] buffer = new byte[1024];
                while ( (byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
            }
        }
        catch (Exception e) {
            logger.error("复制单个文件出错",e);
        }finally {
            try {
                if(inStream != null){
                    inStream.close();
                }
                if(fs != null){
                    fs.flush();
                    fs.close();
                }
            } catch (IOException e) {
                logger.error("IOException",e);
            }
        }
    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {

        try {
            //如果文件夹不存在 则建立新文件夹
            (new File(newPath)).mkdirs();
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith("/")){
                    temp=new File(oldPath+file[i]);
                }
                else{
                    temp=new File(oldPath+"/"+file[i]);
                }

                if(temp.isFile()){
                    BufferedInputStream input = new BufferedInputStream(new FileInputStream(temp));
                    BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(newPath + "/" +
                            (temp.getName())));
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                //如果是子文件夹
                if(temp.isDirectory()){
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            logger.error("复制整个文件夹内容操作出错",e);
        }

    }

    /**
     * 将json串写入文件中
     * @param basePath ../../../
     * @param filePath x.extendName
     * @param jsonStr
     */
    public static void writeStrToFile(String basePath,String filePath,String jsonStr){
        BufferedWriter writer = null;
        try {
            File file = new File(basePath);
            File paperFile = new File(basePath + filePath);
            if(!file.exists()){
                file.mkdirs();

                if(!paperFile.exists()){
                    paperFile.createNewFile();
                }
            }else{
                if(!paperFile.exists()){
                    paperFile.createNewFile();
                }else{
                    //如果存在该文件 删掉 重新创建
                    paperFile.delete();
                    paperFile.createNewFile();
                }
            }
            writer = new BufferedWriter(new FileWriter(basePath + filePath));
            writer.write(jsonStr);
            writer.flush();
        }catch (Exception e){
            logger.error("文件写入失败",e);
        }finally {
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    logger.error("IOException",e);
                }
            }
        }
    }

    public static void writeStrToFile2(String basePath,String filePath,String jsonStr){
        Writer writer = null;
        try {
            File file = new File(basePath);
            File paperFile = new File(basePath + filePath);
            if(!file.exists()){
                file.mkdirs();

                if(!paperFile.exists()){
                    paperFile.createNewFile();
                }
            }else{
                if(!paperFile.exists()){
                    paperFile.createNewFile();
                }else{
                    //如果存在该文件 删掉 重新创建
                    paperFile.delete();
                    paperFile.createNewFile();
                }
            }
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(basePath + filePath), "UTF-8"));
            writer.write(jsonStr);
            writer.flush();
        }catch (Exception e){
            logger.error("文件写入失败",e);
        }finally {
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    logger.error("IOException",e);
                }
            }
        }
    }

    /**
     * 下载
     * @param filePath
     */
    public static Boolean download(String filePath, HttpServletResponse response){
        Boolean status = true;

        try {
        File file = new File(filePath);
        if(!file.exists()){
            return false;
        }
        //得到文件名
        String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
        //把文件名按UTF-8取出并按ISO8859-1编码，保证弹出窗口中的文件名中文不乱码，中文不要太多，最多支持17个中文，因为header有150个字节限制。
        fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
        //告诉浏览器输出内容为流
        response.setContentType("application/octet-stream");
        //Content-Disposition中指定的类型是文件的扩展名，并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的，点保存后，文件以filename的值命名，保存类型以Content中设置的为准。
            // 注意：在设置Content-Disposition头字段之前，一定要设置Content-Type头字段。
        response.addHeader("Content-Disposition", "attachment;filename="+fileName);
            String len = String.valueOf(file.length());
            //设置内容长度
            response.setHeader("Content-Length", len);
            OutputStream out = response.getOutputStream();
            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while((n=in.read(b))!=-1){
                out.write(b, 0, n);
            }
            in.close();
            out.close();
        } catch (IOException e) {
            logger.error("IOException",e);
            status = false;
        }finally {
            FileUtil.deleteFile(filePath);
        }
        return status;
    }

    /**
     * 根据byte数组，生成文件
     * @param filePath 文件生成路径
     * @param fileName 文件名
     */
    public static void getFile(byte[] bfile, String filePath,String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath+"/"+fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args){
        File file = new File("C:/Users/devsun/Desktop","123");
        if(!file.exists()){
            file.mkdirs();
        }
        System.out.println(file.getAbsolutePath());
    }

}
